package com.jinhuhang.u2.homemodule;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.jinhuhang.u2.R;
import com.jinhuhang.u2.common.base.BaseFragment;
import com.jinhuhang.u2.entity.HomeData;
import com.jinhuhang.u2.homemodule.adapter.BannerAdapter;
import com.jinhuhang.u2.homemodule.adapter.HomeGridAdapter;
import com.jinhuhang.u2.homemodule.adapter.HomeListAdapter;
import com.jinhuhang.u2.invertmodule.CreditorRightsDetailActivity;
import com.jinhuhang.u2.invertmodule.ExperienceTenderActivity;
import com.jinhuhang.u2.invertmodule.ProjectDetailActivity;
import com.jinhuhang.u2.invertmodule.ScanActivity;
import com.jinhuhang.u2.invertmodule.TenderDetailActivity;
import com.jinhuhang.u2.myselfmodule.engine.invite.InviteActivity;
import com.jinhuhang.u2.myselfmodule.engine.message.detail.MessageDetailActivity;
import com.jinhuhang.u2.myselfmodule.engine.user.UserActivity;
import com.jinhuhang.u2.ui.MainActivity;
import com.jinhuhang.u2.ui.Message;
import com.jinhuhang.u2.ui.WebViewActivity;
import com.jinhuhang.u2.ui.customview.NoScrollListView;
import com.jinhuhang.u2.ui.customview.VerticalTextview;
import com.jinhuhang.u2.ui.customview.banner.BannerPager;
import com.jinhuhang.u2.ui.customview.banner.OnCustomListener;
import com.jinhuhang.u2.util.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Jaeger on 16/8/11.
 * <p>
 * Email: chjie.jaeger@gmail.com
 * GitHub: https://github.com/laobie
 */
public class HomeFragment extends BaseFragment implements HomeContract.View {

    @Bind(R.id.pulltorefresh)
    PullToRefreshScrollView pulltorefresh;
    //    @Bind(R.id.bg)
//    ImageView bg;
    @Bind(R.id.Bannerlist)
    BannerPager Bannerlist;
    @Bind(R.id.ll_dots)
    LinearLayout llDots;
    @Bind(R.id.bannlayout)
    RelativeLayout bannlayout;
    @Bind(R.id.notifytxt)
    VerticalTextview notifytxt;
    @Bind(R.id.recommendlist)
    NoScrollListView recommendlist;
    @Bind(R.id.lay_text)
    LinearLayout mLayText;
    //    @Bind(R.id.gridlist)
//    GridView gridlist;
    private ArrayList<String> titleList = new ArrayList<String>();
    private BannerAdapter bannerAdapter;
    HomeGridAdapter mGridAdapter;
    HomeListAdapter mListAdapter;
    HomeContract.Presenter mPresenter;
    List<HomeData.BannerBean> mBannerBeen = new ArrayList<>();
    List<HomeData.ArticleBean> mAlertBeen = new ArrayList<>();
    List<HomeData.BorrowBean> mBorrowBeen = new ArrayList<>();
    List<HomeData.VirtualBean> mVirtualBeen = new ArrayList<>();

    @OnClick({R.id.introdution, R.id.safe, R.id.activitycenter, R.id.invite})
    public void onclick(View view) {
        Intent intent1;
        switch (view.getId()) {
            case R.id.introdution:
                intent1 = new Intent(getActivity(), ScanActivity.class);
                intent1.putExtra("type", "discrib");
                startActivity(intent1);
                break;
            case R.id.safe:
                Intent intent = new Intent(getActivity(), ScanActivity.class);
                intent.putExtra("type", "creditor");
                startActivity(intent);
                break;
            case R.id.activitycenter:
                EventBus.getDefault().post("jumpActivity");
                break;
            case R.id.invite:
                if (StringUtils.isEmpty(MainActivity.uid)) {
                    Intent intent2 = new Intent(getActivity(), UserActivity.class);
                    intent2.putExtra("type", UserActivity.LOGIN);
                    intent2.putExtra("setType", GestureActivity.share);
                    startActivity(intent2);
                } else {
                    intent1 = new Intent(getActivity(), InviteActivity.class);
                    startActivity(intent1);
                }
                break;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragement_home, container, false);
        ButterKnife.bind(this, view);

        mPresenter = new HomePresenter(this);

        notifytxt.setText(13, 8, R.color.black2);//设置属性
        notifytxt.setTextStillTime(3000);//设置停留时长间隔
        notifytxt.setAnimTime(500);//设置进入和退出的时间间隔

        notifytxt.setFocusable(true);
        notifytxt.setFocusableInTouchMode(true);
        notifytxt.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        notifytxt.setOnItemClickListener(new VerticalTextview.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(getActivity(), MessageDetailActivity.class);
                intent.putExtra("id", mAlertBeen.get(position).getId());
                intent.putExtra("title", mAlertBeen.get(position).getTitle());
                startActivity(intent);
            }
        });
        pulltorefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {


            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                if (networkInfo == null) {
//                    ToastUtils.showShort("网络不可用，请连接网络！");
//                    pullToRefreshScrollView.onRefreshComplete();
//                    return;
                }
                if (MainActivity.userbean != null) {
                    mPresenter.getData(MainActivity.userbean.getUserId());
                } else {
                    mPresenter.getData("0");
                }
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        pulltorefresh.onRefreshComplete();
//                    }
//                }, 2000);
                if (MainActivity.userbean != null) {
                    mPresenter.getData(MainActivity.userbean.getUserId());
                } else {
                    mPresenter.getData("0");
                }
            }
        });
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        notifytxt.startAutoScroll();
        if (MainActivity.userbean != null) {
            mPresenter.getData(MainActivity.userbean.getUserId());
        } else {
            mPresenter.getData("0");
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent(Message event) {/* Do something */
        if (event.value == 0) {
            Intent intent = new Intent(getActivity(), TenderDetailActivity.class);
            intent.putExtra("id", mBorrowBeen.get(event.postion).getId());
            startActivity(intent);
        } else if (event.value == 2) {
            Intent intent = new Intent(getActivity(), ExperienceTenderActivity.class);
            //   intent.putExtra("id",mVirtualBeen.get(0).getId());
            startActivity(intent);
        } else if (event.value == 3) {
            Intent intent = new Intent(getActivity(), ProjectDetailActivity.class);
            intent.putExtra("id", mBorrowBeen.get(event.postion).getId());
            startActivity(intent);
        } else if (event.value == 5) {
            Intent intent = new Intent(getActivity(), CreditorRightsDetailActivity.class);
            intent.putExtra("id", mBorrowBeen.get(event.postion).getId());
            startActivity(intent);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        notifytxt.stopAutoScroll();
        mPresenter.unsubscribe();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        //      EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initdata() {
        //       EventBus.getDefault().register(this);
        bannerAdapter = new BannerAdapter(mBannerBeen, getActivity());
        Bannerlist.setAdapter(bannerAdapter);
        Bannerlist.setCanScroll(true);
        Bannerlist.startScroll(getActivity());
        bannerAdapter.setOnCustomListener(new OnCustomListener() {
            @Override
            public void onCustomerListener(View v, int position) {
                if (!StringUtils.isEmpty(mBannerBeen.get(position).getUrl())) {
                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra("webAddress", mBannerBeen.get(position).getUrl().replace("userId=0","userId="+MainActivity.uid));
                    intent.putExtra("title", mBannerBeen.get(position).getTitle());
                    startActivity(intent);
                }
            }
        });
        mGridAdapter = new HomeGridAdapter();
        mListAdapter = new HomeListAdapter(mBorrowBeen, mVirtualBeen, getActivity());
        recommendlist.setAdapter(mListAdapter);
        recommendlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mVirtualBeen.size() > 0) {
                    if (position == 0) {
                        Intent intent = new Intent(getActivity(), ExperienceTenderActivity.class);
                        startActivity(intent);
                    } else {
                        if (mBorrowBeen.get(position - 1).getType() == 0) {
                            Intent intent = new Intent(getActivity(), TenderDetailActivity.class);
                            intent.putExtra("id", mBorrowBeen.get(position - 1).getId());
                            startActivity(intent);
                        } else if (mBorrowBeen.get(position - 1).getType() == 3||mBorrowBeen.get(position - 1).getType() == 1) {
                            Intent intent = new Intent(getActivity(), ProjectDetailActivity.class);
                            intent.putExtra("id", mBorrowBeen.get(position - 1).getId());
                            startActivity(intent);
                        } else if (mBorrowBeen.get(position - 1).getType() == 5) {
                            Intent intent = new Intent(getActivity(), CreditorRightsDetailActivity.class);
                            intent.putExtra("id", mBorrowBeen.get(position - 1).getId());
                            startActivity(intent);
                        }
                    }
                } else {
                    if (mBorrowBeen.get(position).getType() == 0) {
                        Intent intent = new Intent(getActivity(), TenderDetailActivity.class);
                        intent.putExtra("id", mBorrowBeen.get(position - 1).getId());
                        startActivity(intent);
                    } else if (mBorrowBeen.get(position).getType() == 3) {
                        Intent intent = new Intent(getActivity(), ProjectDetailActivity.class);
                        intent.putExtra("id", mBorrowBeen.get(position - 1).getId());
                        startActivity(intent);
                    } else if (mBorrowBeen.get(position).getType() == 5) {
                        Intent intent = new Intent(getActivity(), CreditorRightsDetailActivity.class);
                        intent.putExtra("id", mBorrowBeen.get(position - 1).getId());
                        startActivity(intent);
                    }
                }
            }
        });
    }

    @Override
    public void setPresenter(HomeContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showData(HomeData data) {
        pulltorefresh.onRefreshComplete();
        if (data == null) return;

        for (HomeData.ArticleBean bean :
                data.getArticle()) {
            titleList.add(bean.getTitle());
        }
        notifytxt.setTextList(titleList);
        mBannerBeen.clear();
        mBannerBeen.addAll(data.getBanner());
        Bannerlist.setOvalLayout(getActivity(), llDots, data.getBanner().size(), R.drawable.sl_dot_homebanner);
        bannerAdapter.notifyDataSetChanged();
        Bannerlist.setCurrentItem(0);
        mBorrowBeen.clear();
        mVirtualBeen.clear();
        mVirtualBeen.addAll(data.getVirtual());
        mBorrowBeen.addAll(data.getBorrow());
        mListAdapter.notifyDataSetChanged();
        titleList.clear();
        mAlertBeen.clear();
        mAlertBeen.addAll(data.getArticle());

    }

}
